<?php

namespace Api\Openapi;


use Core\Env;
use S\Config;
use S\Http;

/**
 * Class Util
 *
 * @package     Api\Openapi
 * @description openapi服务请求工具类
 */
class Util {

    const PRD_URL = "http://openapi.i.beebank.com/";
    const PRD_PULBIC_URL = "https://www.beebank.com/openapi/";
    const TEST_URL = "http://openapi.i.hrbbwx.com/";
    const ERR_CODE_SUCCESS = "2000000";  //成功响应码
    const ERR_CODE_EMPTY_RESPONSE = "3089999";
    const ERR_CODE_ERROR_FORMAT_RESPONSE = "3089998";

    const DEFAULT_TIMEOUT = 60000;  //默认超时时间

    protected static $_err_code;
    protected static $_err_msg;

    /**
     * 发送请求
     *
     * @param       $uri
     * @param array $params
     * @param int   $timeout default 30000
     *
     * @return array
     * @throws \S\Exception
     */
    public static function request($uri, array $params, $timeout = self::DEFAULT_TIMEOUT) {
        $timestamp  = time();
        $get_params = array(
            "appkey" => Config::confSecurity("openapi.app_key"),
            "t"      => $timestamp,
            "m"      => self::getSign($timestamp, array(json_encode($params))),
        );
        $get_strs   = array();
        foreach ($get_params as $key => $val) {
            $get_strs[] = "{$key}={$val}";
        }
        //环境判断 1.是否是正式 2.是否和openapi处于一个网络
        if (!Env::isProductEnv()) {
            $url = self::TEST_URL;
        } else {
            $url = self::PRD_URL;
        }
        $url      = $url . "{$uri}?" . implode("&", $get_strs);
        $response = (new \S\Http($url))->request(\S\Http::METHOD_POST, $url, json_encode($params), array('timeout' => $timeout));

        $result = json_decode($response, true);
        if (!$result) {
            throw new Exception("error format response from openapi");
        }
        if (self::ERR_CODE_SUCCESS != $result["retcode"]) {
            throw new Exception($result["msg"], $result["retcode"]);
        }

        unset($result["retcode"]);
        unset($result["msg"]);

        return $result;
    }

    
    public static function getProductUrl() {
        return self::PRD_PULBIC_URL;
    }


    /**
     * 获取错误码
     *
     * @return int
     */
    public static function getErrCode() {
        return self::$_err_code;
    }

    /**
     * 获取错误资讯
     *
     * @return string
     */
    public static function getErrMsg() {
        return self::$_err_msg;
    }

    /**
     * 计算签名
     *
     * @param       $timestamp
     * @param array $params
     *
     * @return string
     */
    protected static function getSign($timestamp, array $params) {
        $str = '';
        if (!empty($params)) {
            ksort($params);
            $str = array_values($params);
            $str = implode("", $str);
        }

        return substr(md5($timestamp . Config::confSecurity("openapi.app_secret") . $str), 0, 12);
    }

} 